<?php

error_log(date('m-d H:i:s',SYS_TIME).'| send start: | '."\r\n".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."\r\n".json_encode($_REQUEST)."\r\n", 3, CACHE_PATH.'logs/sms_log_'.date('Ymd').'.php');
$accessKeyId = 'LTAI5tPLzaX4pBEAQYWuFww6';
$accessSecret = 'J7fwKMdqoWxXHGbyGtKACKwroOgleM';
$template_id='SMS_463715415';
$sign = '广州法保网';
$code = random(6);//唯一吗，用于扩展验证
if(isset($_GET['mobile']) && !empty($_GET['mobile'])) {
    $mobile = $_GET['mobile'];
} else {
    $mobile = $_SESSION['mobile'];
}


function https_request($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return 'ERROR ' . curl_error($curl);
    }
    curl_close($curl);
    return $data;
}

function xml_to_array($xml)
{
    $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
    $arr=[];
    if (preg_match_all($reg, $xml, $matches)) {
        $count = count($matches[0]);
        for ($i = 0; $i < $count; $i++) {
            $subxml = $matches[2][$i];
            $key = $matches[1][$i];
            if (preg_match($reg, $subxml)) {
                $arr[$key] = xml_to_array($subxml);
            } else {
                $arr[$key] = $subxml;
            }
        }
    }
    return $arr;
}

$target = "https://sms.aliyuncs.com/?";


if (empty($mobile)) {
    exit(-1);
}


function percentEncode($str)
{
    // 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范
    $res = urlencode($str);
    $res = preg_replace('/\+/', '%20', $res);
    $res = preg_replace('/\*/', '%2A', $res);
    $res = preg_replace('/%7E/', '~', $res);
    return $res;
}


function computeSignature($parameters, $accessKeySecret)
{
    // 将参数Key按字典顺序排序
    ksort($parameters);
    // 生成规范化请求字符串
    $canonicalizedQueryString = '';
    foreach ($parameters as $key => $value) {
        $canonicalizedQueryString .= '&' . percentEncode($key)
            . '=' . percentEncode($value);
    }
    // 生成用于计算签名的字符串 stringToSign
    $stringToSign = 'GET&%2F&' . percentencode(substr($canonicalizedQueryString, 1));
    //echo "<br>".$stringToSign."<br>";
    // 计算签名，注意accessKeySecret后面要加上字符'&'
    $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
    return $signature;
}

// 注意使用GMT时间
date_default_timezone_set("GMT");
$dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601规范
$ParamString = "{\"code\":\"" . strval($code) . "\"}";

$data = array(
    // 公共参数
    'SignName' => $sign,
    'Format' => 'XML',
    'Version' => '2017-05-25',
    'AccessKeyId' => $accessKeyId,
    'SignatureVersion' => '1.0',
    'SignatureMethod' => 'HMAC-SHA1',
    'SignatureNonce' => uniqid(),
    'Timestamp' => gmdate($dateTimeFormat),
    // 接口参数
    'Action' => 'SendSms',
    'TemplateCode' => $template_id,
    'PhoneNumbers' => $mobile,
    'TemplateParam' => '{"code":"' . $code . '"}'
);
// 计算签名并把签名结果加入请求参数
//echo $data['Version']."<br>";
//echo $data['Timestamp']."<br>";
$data['Signature'] = computeSignature($data, $accessSecret);
// 发送请求

$result = xml_to_array(https_request($target . http_build_query($data)));
error_log(date('m-d H:i:s',SYS_TIME).'| body: | '."\r\n".json_encode($data)."\r\n".json_encode($result)."\r\n", 3, CACHE_PATH.'logs/sms_log_'.date('Ymd').'.php');
//print_r($result);

//echo "<br><br>" . $target . http_build_query($data);


//增加到本地数据库
$sms_report_db = pc_base::load_model('sms_report_model');
$send_userid = param::get_cookie('_userid') ? intval(param::get_cookie('_userid')) : 0;
$ip = ip();
$new_content = $mobile.':' . $code ;

if(isset($result['SendSmsResponse']['Code']) && $result['SendSmsResponse']['Code'] == "OK")
{
    $sms_report_db->insert(array('mobile'=>$mobile,'posttime'=>SYS_TIME,'id_code'=>$code,'send_userid'=>$send_userid,'status'=>0,'msg'=>$new_content,'return_id'=>$result['SendSmsResponse']['BizId'],'ip'=>$ip));

    echo 0;
}
else
{
    $sms_report_db->insert(array('mobile'=>$mobile,'posttime'=>SYS_TIME,'send_userid'=>$send_userid,'status'=>'-2','msg'=>$new_content,'ip'=>$ip));
    echo -1;
}
